package br.fatec.ads.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.fatec.ads.dao.RespostaDAO;
import br.fatec.ads.exception.DataBaseException;
import br.fatec.ads.exception.RespostaException;
import br.fatec.ads.model.Pergunta;
import br.fatec.ads.model.Resposta;

public class RespostaIncluir extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public RespostaIncluir() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		int idPergunta = 0;
		
		if(!request.getParameter("idPergunta").equals("")){
			idPergunta = Integer.parseInt(request.getParameter("idPergunta"));
		}
		
		session.setAttribute("idPergunta", idPergunta);
		
		request.getRequestDispatcher("cadresposta_i.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			HttpSession session = request.getSession(false);
			Resposta resposta = new Resposta();
			
			Pergunta pergunta = new Pergunta();
			pergunta.setIdPergunta(Integer.parseInt(request.getParameter("idPergunta")));
			
			resposta.setPergunta(pergunta);
			resposta.setDescResposta(request.getParameter("txtDescResposta"));
			resposta.setNroResposta(request.getParameter("txtNroResposta"));
			resposta.setUsuario(session.getAttribute("usuarioDesc").toString());
			
			RespostaDAO respostaDAO = new RespostaDAO();
			
			respostaDAO.incluirResposta(resposta);
			
			request.getRequestDispatcher("RespostaPesquisar?acao=SUCESSO_INCLUIR&idPergunta=" + pergunta.getIdPergunta()).forward(request, response);
		} catch (RespostaException e) {
			request.getRequestDispatcher("cadresposta_i.jsp?acao=erro").forward(request, response);
			e.printStackTrace();
		} catch (DataBaseException e) {
			request.getRequestDispatcher("cadresposta_i.jsp?acao=erro").forward(request, response);
			e.printStackTrace();
		}
	}
}